package com.service;

import com.constant.CommentStateConst;
import com.dao.CommentDao;
import com.dao.OrdersDao;
import com.dto.CommentDto;
import com.dto.CommentForSubmitDto;
import com.dto.CommentListDto;
import com.pojo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentService {

    @Resource
    private CommentDao commentDao;
    @Resource
    private OrdersDao ordersDao;

    public boolean add(CommentForSubmitDto commentForSubmitDto) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentForSubmitDto, comment);
        comment.setId(null);
        comment.setOrdersId(commentForSubmitDto.getId());
        comment.setCreateTime(new Date());
        // 保存评论
        commentDao.insert(comment);
        Orders orders = new Orders();
        orders.setId(commentForSubmitDto.getId());
        orders.setCommentState(CommentStateConst.HAS_COMMENT);
        // 更新订单评论状态
        ordersDao.update(orders);
        return true;
    }


    public CommentListDto getListByBusinessId(Long businessId, Page page) {
        CommentListDto result = new CommentListDto();
        int pageNo = (page.getCurrentPage()-1)*page.getPageNumber();
        List<Comment> commentList = commentDao.selectByPage(businessId,pageNo,page.getPageNumber());

        // 组织返回值
        List<CommentDto> data = new ArrayList<>();

        for(Comment commentTemp : commentList) {
            CommentDto commentDto = new CommentDto();
            commentDto.setOrders(commentTemp.getOrders());
            commentDto.setStar(commentTemp.getStar());
            // 隐藏手机号中间4位
            StringBuffer phoneBuffer = new StringBuffer(String.valueOf(commentTemp.getOrders().getMember().getPhone()));
            commentDto.setUsername(phoneBuffer.replace(3, 7, "****").toString());
            data.add(commentDto);

        }
        result.setData(data);
        result.setHasMore(page.getCurrentPage() < page.getTotalPage());
        return result;
    }
}

